package com.blb.day20231107login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.day20231107login.entity.Permission;
import com.blb.day20231107login.entity.Role;
import com.blb.day20231107login.entity.User;
import com.blb.day20231107login.mapper.UserMapper;
import com.blb.day20231107login.service.IUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义登录逻辑
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private IUserService userService;

    /**
     * 通过用户名查询用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //按用户名查询用户
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询授权集合
        List<GrantedAuthority> authorities = userService.getAuthoritiesByUsername(username);
        //将用户信息和授权包装到User对象中返回给Security
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities);
    }
}
